package com.example.myapplication;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 设备数据上传服务
 * 负责将设备数据上传到服务器
 */
public class DeviceDataUploader {
    
    private static final String TAG = "DeviceDataUploader";
    private static final String UPLOAD_ENDPOINT = "/device/data/upload";
    
    private final Context context;
    private final DeviceDataConfig config;
    private final Gson gson;
    
    public DeviceDataUploader(Context context) {
        this.context = context.getApplicationContext();
        this.config = new DeviceDataConfig(context);
        this.gson = new Gson();
    }
    
    /**
     * 上传设备数据
     * @param data 设备数据模型
     * @param callback 上传回调
     */
    public void uploadData(DeviceDataModel data, UploadCallback callback) {
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                String serverUrl = config.getServerUrl();
                String uploadUrl = serverUrl + UPLOAD_ENDPOINT;
                
                URL url = new URL(uploadUrl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                connection.setRequestProperty("Accept", "application/json");
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(30000);
                connection.setDoOutput(true);
                
                // 将数据转换为JSON
                String jsonData = gson.toJson(data);
                
                // 发送数据
                try (OutputStream outputStream = connection.getOutputStream()) {
                    byte[] input = jsonData.getBytes("UTF-8");
                    outputStream.write(input, 0, input.length);
                }
                
                // 获取响应
                int responseCode = connection.getResponseCode();
                
                if (responseCode == HttpURLConnection.HTTP_OK || 
                    responseCode == HttpURLConnection.HTTP_CREATED) {
                    
                    // 读取响应
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(inputStream, "UTF-8"));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    
                    if (callback != null) {
                        callback.onSuccess(response.toString());
                    }
                    
                    Log.d(TAG, "数据上传成功: " + response.toString());
                } else {
                    String errorMessage = "上传失败，状态码: " + responseCode;
                    Log.e(TAG, errorMessage);
                    
                    if (callback != null) {
                        callback.onError(errorMessage);
                    }
                }
                
            } catch (Exception e) {
                Log.e(TAG, "上传数据失败", e);
                if (callback != null) {
                    callback.onError("上传错误: " + e.getMessage());
                }
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }
    
    /**
     * 上传设备数据（同步版本）
     * @param data 设备数据模型
     * @return 上传结果
     */
    public UploadResult uploadDataSync(DeviceDataModel data) {
        HttpURLConnection connection = null;
        try {
            String serverUrl = config.getServerUrl();
            String uploadUrl = serverUrl + UPLOAD_ENDPOINT;
            
            URL url = new URL(uploadUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(30000);
            connection.setDoOutput(true);
            
            // 将数据转换为JSON
            String jsonData = gson.toJson(data);
            
            // 发送数据
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = jsonData.getBytes("UTF-8");
                outputStream.write(input, 0, input.length);
            }
            
            // 获取响应
            int responseCode = connection.getResponseCode();
            
            if (responseCode == HttpURLConnection.HTTP_OK || 
                responseCode == HttpURLConnection.HTTP_CREATED) {
                
                // 读取响应
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                
                return new UploadResult(true, response.toString(), null);
            } else {
                String errorMessage = "上传失败，状态码: " + responseCode;
                return new UploadResult(false, null, errorMessage);
            }
            
        } catch (Exception e) {
            Log.e(TAG, "上传数据失败", e);
            return new UploadResult(false, null, "上传错误: " + e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    /**
     * 上传回调接口
     */
    public interface UploadCallback {
        void onSuccess(String response);
        void onError(String error);
    }
    
    /**
     * 上传结果
     */
    public static class UploadResult {
        private final boolean success;
        private final String response;
        private final String error;
        
        public UploadResult(boolean success, String response, String error) {
            this.success = success;
            this.response = response;
            this.error = error;
        }
        
        public boolean isSuccess() {
            return success;
        }
        
        public String getResponse() {
            return response;
        }
        
        public String getError() {
            return error;
        }
    }
}

